/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package east2west.action;

import east2west.dto.CustomerDTO;
import east2west.dto.JobDTO;
import east2west.dto.LocationDTO;
import east2west.dto.SchedulesLocationDTO;
import east2west.dto.TourCancelDTO;
import east2west.dto.TourDTO;
import east2west.dto.TourOrderDTO;
import east2west.dto.TourOrderDetailDTO;
import east2west.dto.TourPriceDTO;
import east2west.dto.TourServiceDTO;
import east2west.dto.TourTypeDTO;
import east2west.service.CustomerService;
import east2west.service.JobService;
import east2west.service.LocationService;
import east2west.service.TourService;
import east2west.util.DateTimeUtil;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 *
 * @author nguyendat
 */
public class TourAction extends DispatchAction {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String ERR = "err";
    TourService tourSer = null;
    float sumPrice = 0;
    float min = 0;
    float max = 0;
    float minP = 0;
    float maxP = 0;
    JobService jobSer = null;
    LocationService locationser = null;
    CustomerService cusSer = null;

    public ActionForward detail(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        tourSer = new TourService();
        locationser = new LocationService();
//------------------------------------------------------------------------------------------
        //Definy ArrayList
        ArrayList<TourDTO> listTour = new ArrayList<TourDTO>();
        ArrayList<SchedulesLocationDTO> listLocation = new ArrayList<SchedulesLocationDTO>();
        ArrayList<TourPriceDTO> avgListPrice = new ArrayList<TourPriceDTO>();
        ArrayList<TourDTO> listOrtherTour = new ArrayList<TourDTO>();
        ArrayList<TourDTO> listShowTopMn = new ArrayList<TourDTO>();
        ArrayList<TourDTO> listMaxMinPrice = new ArrayList<TourDTO>();
        ArrayList<TourService> listService = new ArrayList<TourService>();
//-----------------------------------------------------------------------------------------
        listShowTopMn = tourSer.findByTourShowTopMenu();
        request.setAttribute("listShowTourMn", listShowTopMn);

        int id = Integer.parseInt(request.getParameter("id"));
        TourDTO tourDTO = tourSer.findById(id);

        listLocation = tourSer.showLocationTourName(id);

        listService = tourSer.getServiceName(id);

        listOrtherTour = tourSer.findByOrtherTour(id);



        min = tourSer.getMin(id);
        request.setAttribute("min", min);
        max = tourSer.getMax(id);
        request.setAttribute("max", max);

        avgListPrice = tourSer.listavgPrice(id);
        request.setAttribute("avgListPrice", avgListPrice);
        listTour = tourSer.readByAll();
        //--------------------------------------------------------
        for (Iterator<TourDTO> it = listOrtherTour.iterator(); it.hasNext();) {
            TourDTO tourDTOP = it.next();
            int idp = tourDTOP.getTourDetailDTO().getTourId();
            minP = tourSer.getMin(idp);
            maxP = tourSer.getMax(idp);
            tourDTOP.setMinP(minP);
            tourDTOP.setMaxP(maxP);
            listMaxMinPrice.add(tourDTOP);
        }

        //request attribute access

        request.setAttribute("listMaxMinPrice", listMaxMinPrice);
        request.setAttribute("listTour", listTour);
        request.setAttribute("tourDTO", tourDTO);
        request.setAttribute("listLocation", listLocation);
        request.setAttribute("listOrtherTour", listOrtherTour);
        request.setAttribute("listService", listService);
        request.setAttribute("pages", "Tours");
        request.setAttribute("id", id);
        request.setAttribute("page", "tourdetail.page");

        return mapping.findForward(SUCCESS);

    }

    public ActionForward booking(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //---------------------------------------------------------------------------------------
        tourSer = new TourService();
        jobSer = new JobService();
        HttpSession session = request.getSession(true);

        ArrayList<TourPriceDTO> avgListPrice = new ArrayList<TourPriceDTO>();
        ArrayList<JobDTO> listJob = new ArrayList<JobDTO>();
        ArrayList<TourServiceDTO> listServicename = new ArrayList<TourServiceDTO>();
        ArrayList<TourDTO> listCart = new ArrayList<TourDTO>();
        //----------------------------------------------------------------------------cartTour
        int id = Integer.parseInt(request.getParameter("id"));
        int idp = Integer.parseInt(request.getParameter("idp"));
        //-------------------------------------------------------------
        TourPriceDTO priceDTO = new TourPriceDTO();
        TourOrderDetailDTO tourOrderDetailDto = new TourOrderDetailDTO();
        //-----------------------------------------------------------------
        priceDTO = tourSer.findByTourPriceId(idp);
        listCart.add(tourSer.findById(id));
        listJob = jobSer.readByAll();
        sumPrice = priceDTO.getPrice() + tourSer.getSumPriceTourDetail(id);
        tourOrderDetailDto.setAmount(sumPrice);
        listServicename = tourSer.getServiceName(id);


        avgListPrice = tourSer.listavgPrice(id);

//------------------------------------------------------------------------
        session.setAttribute("listServiceName", listServicename);
        session.setAttribute("sumPrice", sumPrice);
        session.setAttribute("cartTour", listCart);
        session.setAttribute("priceDTO", priceDTO);
        session.setAttribute("tourOrderDetailDto", tourOrderDetailDto);
        request.setAttribute("avg", avgListPrice);
        session.setAttribute("listJob", listJob);
        //request.setAttribute("getPriceId", getPriceId);
        //--------------------------------------------------------------------


        request.setAttribute("page", "booking.page");
        //----------------------------------------------------------------------------

        return mapping.findForward(SUCCESS);
    }

    public ActionForward listTour(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        tourSer = new TourService();
        ArrayList<TourDTO> listTour = new ArrayList<TourDTO>();
        ArrayList<TourDTO> listTourMinMax = new ArrayList<TourDTO>();
        listTour = tourSer.readByAll();
        for (Iterator<TourDTO> it = listTour.iterator(); it.hasNext();) {
            TourDTO tourDTO = it.next();
            int id = tourDTO.getTourId();
            max = tourSer.getMax(id);
            min = tourSer.getMin(id);
            tourDTO.setMin(min);
            tourDTO.setMax(max);
            listTourMinMax.add(tourDTO);
            TourPriceDTO getPriceId = tourSer.getPriceIdTop(id);
            tourDTO.setTourPriceDTO(getPriceId);

        }

        request.setAttribute("listTour", listTourMinMax);
        request.setAttribute("page", "tourlist.page");
        //------------------------------------------------

        return mapping.findForward(SUCCESS);
    }

    public ActionForward Submit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();

        tourSer = new TourService();
        cusSer = new CustomerService();
        CustomerDTO cusDTO = new CustomerDTO();
        jobSer = new JobService();
        int orderId = 0;
        ArrayList<TourDTO> cartTour = (ArrayList<TourDTO>) session.getAttribute("cartTour");
        TourOrderDetailDTO tourOrderDetailDto = new TourOrderDetailDTO();
        TourOrderDTO tourOrderDTo = new TourOrderDTO();
        //--------------------------------------------------------------------
        cusDTO.setEmail(request.getParameter("email"));
        cusDTO.setFullName(request.getParameter("fullName"));
        cusDTO.setPhone(request.getParameter("phone"));
        cusDTO.setFax(request.getParameter("fax"));
        cusDTO.setBirthDay(request.getParameter("birth"));
        cusDTO.setCountry(request.getParameter("country"));
        cusDTO.setState(request.getParameter("state"));
        cusDTO.setAddress(request.getParameter("add"));
        JobDTO jobDTO = jobSer.findById(Integer.parseInt(request.getParameter("jobId")));
        cusDTO.setJobId(jobDTO.getJobId());
        if (cusSer.findByEmail(cusDTO.getEmail()) == null) {
            int cusId = cusSer.create(cusDTO);
            if (cusId > 0) {
                cusDTO.setCustomerId(cusId);

                tourOrderDTo.setCustId(cusId);
                tourOrderDTo.setOrderDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
                // tourOrderDTo.setIsDelete(true);
                orderId = tourSer.create(tourOrderDTo);
                if (orderId > 0) {
                    //  tourOrderDetailDto =new TourOrderDetailDTO();
                    tourOrderDetailDto.setOrderId(orderId);
                    tourOrderDetailDto.setTourId(Integer.parseInt(request.getParameter("tourId")));
                    tourOrderDetailDto.setTotalQty(Integer.parseInt(request.getParameter("txtAdultQty")));
                    tourOrderDetailDto.setChildQty(Integer.parseInt(request.getParameter("txtChildQty")));
                    tourOrderDetailDto.setStartDate(request.getParameter("theDate"));
                    tourOrderDetailDto.setAmount(Float.parseFloat(request.getParameter("total")));
                    tourSer.create(tourOrderDetailDto);
                }
            }
        } else {
            cusDTO.setCustomerId(cusSer.findByEmail(cusDTO.getEmail()).getCustomerId());

            tourOrderDTo.setCustId(cusSer.findByEmail(cusDTO.getEmail()).getCustomerId());
            tourOrderDTo.setOrderDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
            // tourOrderDTo.setIsDelete(true);
            orderId = tourSer.create(tourOrderDTo);
            if (orderId > 0) {
                tourOrderDetailDto.setOrderId(orderId);
                tourOrderDetailDto.setTourId(Integer.parseInt(request.getParameter("tourId")));
                tourOrderDetailDto.setTotalQty(Integer.parseInt(request.getParameter("txtAdultQty")));
                tourOrderDetailDto.setChildQty(Integer.parseInt(request.getParameter("txtChildQty")));
                tourOrderDetailDto.setStartDate(request.getParameter("theDate"));
                tourOrderDetailDto.setAmount(Float.parseFloat(request.getParameter("total")));
                tourSer.create(tourOrderDetailDto);
            }
        }
        //----------------------------------------
        request.setAttribute("cartTour", cartTour);
        request.setAttribute("tourOrderDetailDto", tourOrderDetailDto);
        request.setAttribute("cus", cusDTO);
        request.setAttribute("jobDTO", jobDTO);
        request.setAttribute("orderId", orderId);
        session.invalidate();
        request.setAttribute("page", "contact.page");
        return mapping.findForward(SUCCESS);

    }

    public ActionForward searchTour(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        tourSer = new TourService();
        //HttpSession session = request.getSession();
        //String tourName = request.getParameter("tourName");
        TourDTO dto = new TourDTO();
//   if(tourName.equals("")){
//       dto.setTourName(null);
//   }else
//   {
//         dto.setTourName(tourName);
//   }
        String departure = request.getParameter("departure");
//     if(departure.equals("Departure")){
//         dto.setDeparture(null);
//     }else{
        dto.setDeparture(departure);
        // }
        String destination = request.getParameter("destination");
        //  if(destination.equals("Destination")){
        //   dto.setDestination(null);
        // }else
        //  {
        dto.setDestination(destination);
        //  }
        String duaration = request.getParameter("duration");

        dto.setDuration(Integer.parseInt(duaration));


        //  if(duration<=0){
        //     dto.setDuration(10000);
        // }else

        String typeName = request.getParameter("typeName");
        TourTypeDTO type = new TourTypeDTO();
        // if(typeName.equals("PackageTour")){
        // type.setTourTypeName(null);
        //  dto.setTourTypeDTO(type);

        // }else
        // {
        type.setTourTypeName(typeName);
        dto.setTourTypeDTO(type);
        // }
        String locationName = request.getParameter("locationName");
        LocationDTO location = new LocationDTO();
//     if(locationName.equals("Location")){
//         location.setLocationName(null);
//         dto.setLocationDTO(location);
//     }else
//     {
        location.setLocationName(locationName);
        dto.setLocationDTO(location);
//
//     }
        ArrayList<TourDTO> listSearchTour = new ArrayList<TourDTO>();
        ArrayList<TourDTO> listSearch = tourSer.listSearch(dto);
        for (Iterator<TourDTO> it = listSearch.iterator(); it.hasNext();) {
            TourDTO tourDTO = it.next();
            int id = tourDTO.getTourId();
            max = tourSer.getMax(id);
            min = tourSer.getMin(id);
            tourDTO.setMin(min);
            tourDTO.setMax(max);
            TourPriceDTO getPriceId = tourSer.getPriceIdTop(id);
            tourDTO.setTourPriceDTO(getPriceId);

            listSearchTour.add(tourDTO);

        }

        request.setAttribute("listSearch", listSearchTour);
        request.setAttribute("page", "tourlists.page");

        return mapping.findForward(SUCCESS);
    }

    public ActionForward CancelOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        int num = Integer.parseInt(request.getParameter("num"));
        ArrayList<TourCancelDTO> listcancelDTO = new ArrayList<TourCancelDTO>();
        tourSer = new TourService();
        boolean flag = true;
        float money = 0;
        for (int i = 1; i <= num; i++) {
            TourCancelDTO cancelDTO = new TourCancelDTO();
            cancelDTO.setOrderDetailId(Integer.parseInt(request.getParameter("detailId" + i)));
            cancelDTO.setDiscount(Float.parseFloat(request.getParameter("money" + i)));
            cancelDTO.setCancelDate(DateTimeUtil.nowDate("MM/dd/yyyy"));
            if (!tourSer.create(cancelDTO)) {
                flag = false;
            }
            money += cancelDTO.getDiscount();
            listcancelDTO.add(cancelDTO);
        }
        if (flag) {
            request.setAttribute("listCancel", listcancelDTO);
            request.setAttribute("money", money);
            request.setAttribute("page", "carcancelreport.page");
            return mapping.findForward(SUCCESS);
            //thong bao so tien dc nhan lai
        } else {
            //thong bao chua huy dc
            request.setAttribute("listCancel", listcancelDTO);
            request.setAttribute("num", num);
            return mapping.findForward(ERR);
        }
    }
    //localtion

    public ActionForward localtion(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        tourSer = new TourService();

        int id = Integer.parseInt(request.getParameter("id"));
        LocationDTO localtionDTO = tourSer.getLocaltionById(id);

        request.setAttribute("localtionDTO", localtionDTO);
        request.setAttribute("pages", "Tours");
        request.setAttribute("page", "localtion.page");

        return mapping.findForward(SUCCESS);

    }
}
